from django.contrib.auth import get_user_model, backends
# from utils.getSK import GetSk
from rest_framework.authentication import SessionAuthentication

UserModel = get_user_model()


class WeChatOpenidAuth(backends.ModelBackend):

    def get_user(self, user_id):

        try:
            user = UserModel._default_manager.get(pk=user_id)
        except UserModel.DoesNotExist:
            return None
        return user if self.user_can_authenticate(user) else None

    def user_can_authenticate(self, user):
        """
        Reject users with is_active=False. Custom user models that don't have
        that attribute are allowed.
        """
        is_active = getattr(user, 'is_active', None)
        isDelete = getattr(user, 'isDelete', None)
        return (is_active or is_active is None) and (not isDelete)

    def authenticate(self, request, username=None, password=None):
        # GetSk()

        login_type = True
        if username is None:
            username = 'openId'
        try:
            user = UserModel.objects.get_by_natural_key(username)
            login_type = UserModel.objects.get_login_type()
        except UserModel.DoesNotExist:
            pass
        else:
            if login_type != -1:
                if login_type == 0:
                    try:

                        if user.check_password(password) and self.user_can_authenticate(user):
                            print(request.session.get('user_id'))
                            return user
                    except Exception as e:
                        print('异常', e)
                else:
                    return user


class CsrfExemptSessionAuthentication(SessionAuthentication):
    def enforce_csrf(self, request):
        return  # To not perform the csrf check previously happening
